#include "EV1527.h"
#include "at32f421_wk_config.h"

extern uint16_t  g_ulCaptureBuffer[DMA1_CHANNEL5_BUFFER_SIZE];

extern uint8_t g_ucDataReady ;                        // 数据就绪标志
extern uint32_t g_ulChipID ;                          // 解码后的芯片ID
extern uint8_t g_ucKeyCode ;                          // 解码后的按键码
extern uint8_t g_Stat ;                            // 状态标志  


void EV1527_ProcessData(void) {
    if (!g_ucDataReady) return;

    // 计算脉冲宽度
    uint16_t pulse_width[DMA1_CHANNEL5_BUFFER_SIZE - 1];
    for (uint8_t i = 0; i < DMA1_CHANNEL5_BUFFER_SIZE - 1; i++) {
        pulse_width[i] = (g_ulCaptureBuffer[i + 1] - g_ulCaptureBuffer[i]) & 0xFFFF;
    }

    // 查找引导码，限制查找次数，防止超时
    uint8_t start_index = 0;
    uint8_t found_lead_code = 0;
    uint8_t search_attempts = 0;  // 记录查找次数
    const uint8_t SEARCH_LIMIT = 100;  // 设定最大搜索次数，避免死循环

    for (uint8_t i = 0; i < DMA1_CHANNEL5_BUFFER_SIZE - 1; i++) {
        search_attempts++;
        if (search_attempts > SEARCH_LIMIT) {
            g_ucDataReady = 0;  // 超时退出
            return;
        }

        if (pulse_width[i] < BIT0_LOW_MIN_US) {
            i++; // 跳过无效低电平后的高电平
            continue;
        }

        if (pulse_width[i] >= LEAD_CODE_MIN_US && pulse_width[i] <= LEAD_CODE_MAX_US) {
            start_index = i + 1;  // 记录引导码结束后的位置
            found_lead_code = 1; 
            break;
        }
    }

    // 未找到引导码，直接退出
    if (!found_lead_code || start_index + 2 * EV1527_BIT_COUNT >= DMA1_CHANNEL5_BUFFER_SIZE - 1) {
        g_ucDataReady = 0;
        return;
    }

    // 提取24位数据
    uint32_t decoded_data = 0;
    for (uint8_t bit = 0; bit < EV1527_BIT_COUNT; bit++) {
        uint32_t low_time = pulse_width[start_index + 2 * bit + 1];  // 低电平时间

        if (low_time >= BIT0_LOW_MIN_US && low_time <= BIT0_LOW_MAX_US) {
            decoded_data <<= 1;  // 0码
        } else if (low_time >= BIT1_LOW_MIN_US && low_time <= BIT1_LOW_MAX_US) {
            decoded_data = (decoded_data << 1) | 0x01;  // 1码
        } else {
            g_ucDataReady = 0;
            return;  // 数据错误
        }
    }

    // 提取芯片ID和按键码
    g_ulChipID = (decoded_data >> 4) & 0x000FFFFF;  // 20位芯片ID
    g_ucKeyCode = decoded_data & 0x0F;              // 4位按键码
    g_ucDataReady = 0;  // 数据已处理，清空标志位
    g_Stat = 1;
    printf("芯片ID: %lu, 按键码: %u\n", g_ulChipID, g_ucKeyCode);
}



